package com.cloud.mqtt.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @Author: JohnCoding
 * @Description:
 * @date: 2020/7/16 11:51
 */
public class GzipUtil {


//    /**
//     * Gzip解压
//     * @param payload
//     * @return
//     */
//    public static String unCompress(byte[] payload){
//        ByteArrayInputStream in = new ByteArrayInputStream(payload);
//        try {
//            GzipCompressorInputStream gzip = new GzipCompressorInputStream(in);
//            //缓冲容器
//            byte[] flush = new byte[2000];
//            //接收长度
//            int len = -1;
//            while ((len = gzip.read(flush)) != -1) {
//                String str = new String(flush, 0, len);
//                return str;
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }


    public static String compress(String str,String inEncoding){
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            GZIPOutputStream gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(inEncoding));
            gzip.close();
            return out.toString("ISO-8859-1");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String unCompress(String str,String outEncoding){
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString(outEncoding);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static void main(String[] args) throws Exception{
        String str = "\u001F       «V*Î\u008BOÎOIU²R220430402064 \u0002C%\u001D¥\u0094Ä\u0092D%«èj%\u0088\u0012\u0003\u0098\u0088¡y\u00AD\u000ELÐ\u0010&h\u0080\u00103Â\"f\u008C\u0010\u008B\u00AD\u0005 >\u0096\u008E\u0017x   ";
        String compress1 = compress(str, "UTF-8");
//        byte[] compress1 = DefalterUtil.compress(str.getBytes());
        System.out.println(compress1);
        String uncompress1 = unCompress(compress1, "UTF-8");
//        String uncompress1 = DefalterUtil.unCompress(compress1);
        System.out.println(uncompress1);
    }




}
